<script lang="ts" setup>
import { ref, onMounted, reactive, computed, h } from 'vue'
import dayjs from 'dayjs'
import {
  deletePictureUsingPost, doPictureReviewUsingPost, editPictureUsingPost,
  listPictureByPageUsingPost, listPictureTagCategoryUsingGet
} from '@/servers/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { DeleteOutlined, EditOutlined } from '@ant-design/icons-vue'
import UploadForm from '@/components/upload-form/index.vue'
import {
  PictureReviewStatus,
  PictureReviewStatusMap,
  PictureReviewStatusOptions
} from '@/constants/picture.ts'
import { useRouter } from 'vue-router'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '图片',
    dataIndex: 'url'
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true
  },
  {
    title: '类型',
    dataIndex: 'category'
  },
  {
    title: '标签',
    dataIndex: 'tags'
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo'
  },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage'
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime'
  },
  {
    title: '操作',
    key: 'action'
  }
]

const router = useRouter()
// 数据
const dataList = ref([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
  reviewStatus: ''
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`
  }
})

// 获取数据
const fetchData = async () => {
  const res = await listPictureByPageUsingPost({
    ...searchParams
  })
  if (res.data) {
    dataList.value = res.data.records ?? []
    total.value = res.data.total ?? 0
  }
}

// 获取数据
const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1
  fetchData()
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 删除
const deletePicture = async (id: number) => {
  const res = await deletePictureUsingPost({ id })
  if (res.code == 200) {
    message.success('删除成功')
    await fetchData()
  }
}

// 审核操作
const handleReview = async (row: API.Picture, state: number) => {
  // 校验参数
  if (row == null || state == null) {
    message.error('请传入数据')
    return
  }
  // 请求接口
  const res = await doPictureReviewUsingPost({
    id: row.id,
    reviewStatus: state,
    reviewMessage: state == PictureReviewStatus.PASS ? '管理员自动审核通过' : '管理员自动审核拒绝'
  })
  if (res.code == 200) {
    // 刷新数据
    await fetchData()
  }
}

/** 编辑模块 */
const editModal = ref<boolean>(false)
// 编辑数据
const editData = ref<API.Picture>({})
// 分类选项
const categoryOptions = ref<string[]>([])
// 标签选项
const tagOptions = ref<string[]>([])

// 图片上传成功
const uploadSuccess = (newPicture: API.PictureVO) => {
  editData.value.url = newPicture.url
}
// 编辑按钮点击
const editBtnClick = (row: API.Picture) => {
  editData.value = { ...row }
  // 格式化 tags
  if (row.tags) {
    editData.value.tags = JSON.parse(editData.value.tags)
  } else {
    editData.value.tags = []
  }
  editModal.value = true
}

// 编辑表单提交
const handleOk = async () => {
  // 请求接口编辑数据
  const res = await editPictureUsingPost(editData.value)
  if (res.code == 200) {
    editModal.value = false
    message.success('编辑成功')
    await fetchData()
  }
}

// 获取标签和分类选项
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.code == 200 && res.data) {
    // 转换成下拉选项组件接受的格式
    tagOptions.value = (res.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data
      }
    })
    categoryOptions.value = (res.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data
      }
    })
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
  getTagCategoryOptions()
})
</script>

<template>
  <div>
    <!-- 搜索 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="关键词" name="searchText">
        <a-input
          v-model:value="searchParams.searchText"
          placeholder="从名称和简介搜索"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="类型" name="category">
        <a-input v-model:value="searchParams.category" placeholder="请输入类型" allow-clear />
      </a-form-item>
      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="searchParams.tags"
          mode="tags"
          placeholder="请输入标签"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="审核状态" name="reviewStatus">
        <a-select
          ref="select"
          v-model:value="searchParams.reviewStatus"
          :options="PictureReviewStatusOptions"
          placeholder="请选择审核状态"
          style="width: 120px"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>
    <!-- 操作栏 -->
    <div class="toolbar">
      <a-button type="primary" href="/picture/add" target="_blank">+ 上传图片</a-button>
      <a-button type="primary" href="/picture/upload/batch" target="_blank">+ 批量上传</a-button>
    </div>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      :scroll="{ x: 'max-content', y: 500 }"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <a-image :src="record.url" :width="65" />
        </template>
        <!-- 标签 -->
        <template v-if="column.dataIndex === 'tags'">
          <a-space v-if="record.tags != null" wrap>
            <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">{{ tag }}</a-tag>
          </a-space>
          <span v-else></span>
        </template>
        <!-- 图片信息 -->
        <template v-if="column.dataIndex === 'picInfo'">
          <div>格式：{{ record.picFormat }}</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>宽高比：{{ record.picScale }}</div>
          <div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
        </template>
        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'reviewMessage'">
          <div>审核状态：{{ PictureReviewStatusMap[record.reviewStatus] }}</div>
          <div>审核信息：{{ record.reviewMessage }}</div>
          <div>审核人：{{ record.reviewerId }}</div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space wrap>
            <a-button v-if="record.reviewStatus != PictureReviewStatus.PASS" type="link"
                      @click="handleReview(record, PictureReviewStatus.PASS)">通过
            </a-button>
            <a-button v-if="record.reviewStatus != PictureReviewStatus.REJECT" type="link" danger
                      @click="handleReview(record, PictureReviewStatus.REJECT)">
              拒绝
            </a-button>
            <a-button type="link" :icon="h(EditOutlined)" @click="editBtnClick(record)">编辑
            </a-button>
            <a-button type="link" danger :icon="h(DeleteOutlined)"
                      @click="deletePicture(record.id)">删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>
    <!-- 弹窗 -->
    <a-modal v-model:open="editModal" title="编辑图片" @ok="handleOk">
      <div>
        <UploadForm :picture="editData" :on-success="uploadSuccess" />
      </div>
      <a-form :model="editData" @finish="handleOk">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="editData.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="分类" name="category">
          <a-auto-complete
            v-model:value="editData.category"
            :options="categoryOptions"
            placeholder="请输入分类"
            allowClear
            style="width: 100%;"
          />
        </a-form-item>
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="editData.tags"
            :options="tagOptions"
            mode="tags"
            placeholder="请输入标签"
            allowClear
            style="width: 100%;"
          />
        </a-form-item>
        <a-form-item label="简介" name="introduction">
          <a-textarea
            v-model:value="editData.introduction"
            placeholder="请输入简介"
            :auto-size="{ minRows: 2, maxRows: 5 }"
            allowClear
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="scss" scoped>
.toolbar {
  margin: 10px 0;
  display: flex;
  align-items: center;
  justify-content: start;
  gap: 10px;
}
</style>

